package com.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.constant.CartConstant;
import com.guli.common.to.SkuInfoTo;
import com.guli.common.utils.R;
import com.gulimall.cart.feign.ProductFeign;
import com.gulimall.cart.interceptor.CartInterceptor;
import com.gulimall.cart.service.CartService;
import com.gulimall.cart.vo.Cart;
import com.gulimall.cart.vo.CartItem;
import com.gulimall.cart.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductFeign productFeign;
    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> boundHashOps = getHashOps();
        String res = (String) boundHashOps.get(skuId.toString());
        //结果不为空
        if (!StringUtils.isEmpty(res)) {
            //购物车有此商品
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            boundHashOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
        //远程查询当前要添加的商品的信息
        CartItem cartItem = new CartItem();
        CompletableFuture<Void> skuInfo = CompletableFuture.runAsync(() -> {
            R info = productFeign.skuInfo(skuId);
            if ((Integer) info.get("code") == 0) {
                String jsonString = JSON.toJSONString(info.get("skuInfo"));
                SkuInfoTo skuInfoTo = JSON.parseObject(jsonString, new TypeReference<SkuInfoTo>() {
                });
                //将商品添加到购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfoTo.getSkuDefaultImg() == null ? "" : skuInfoTo.getSkuDefaultImg());
                cartItem.setTitle(skuInfoTo.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfoTo.getPrice());
            }
        }, executor);
        //远程查询sku的组合查询信息
        CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
            List<String> skusaleattrvalue = productFeign.getSkusaleattrvalue(skuId);
            cartItem.setSkuAttr(skusaleattrvalue);
        }, executor);
        try {
            CompletableFuture.allOf(skuInfo, getSkuSaleAttrValues).get();
        } catch (InterruptedException | ExecutionException ex) {
            throw new RuntimeException(ex);
        }
        String str = JSON.toJSONString(cartItem);
        boundHashOps.put(skuId.toString(), str);
        return cartItem;
    }

    private BoundHashOperations<String, Object, Object> getHashOps() {
        //获取当前线程
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //用户已登录
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        } else {
            //用户未登录
            cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> boundHashOps = stringRedisTemplate.boundHashOps(cartKey);
        return boundHashOps;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> hashOps = getHashOps();
        String str = (String) hashOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        // 登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //没登录
        if (userInfoTo.getUserId() == null) {
            String userKey = CartConstant.CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的所有购物项
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setItems(cartItems);
        }
        //已登录
        String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        //如果临时购物车的数据还没有进行合并
        List<CartItem> cartItems = getCartItems(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
        if (cartItems != null) {
            //临时购物车有数据，需要合并
            for (CartItem cartItem : cartItems) {
                addToCart(cartItem.getSkuId(), cartItem.getCount());
            }
            //清空购物车
            clearCart(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
        }
        List<CartItem> itemList = getCartItems(cartKey);
        cart.setItems(itemList);
        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer checked) {
        BoundHashOperations<String, Object, Object> hashOps = getHashOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(checked == 1);
        String carItemJson = JSON.toJSONString(cartItem);
        hashOps.put(skuId.toString(), carItemJson);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> hashOps = getHashOps();
        hashOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> hashOps = getHashOps();
        hashOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        }
        String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);
        List<CartItem> collect = cartItems.stream().filter(CartItem::getCheck)
                .peek(item -> {
                    R r = productFeign.getPrice(item.getSkuId());
                    String data = (String) r.get("data");
                    item.setPrice(new BigDecimal(data));
                })
                .collect(Collectors.toList());
        return collect;

    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values == null || values.size() <= 0) {
            return null;
        }
        List<CartItem> collect = values.stream().map(value -> JSON.parseObject(value.toString(), CartItem.class))
                .collect(Collectors.toList());
        return collect;
    }

    /*
     * 清除购物车
     * */
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

}
